package main

import (
	"time"
	"crypto/md5"
	"encoding/hex"
	"strconv"
	"net/url"
	"strings"
	"net/http"
	"net/http/httputil"
	"log"
)

var AIUIURL = "http://openapi.xfyun.cn/v2/aiui/entity/upload-resource"


var X_Nonce = "100"

var ENTITYDATA = `{"song":"给我一首歌的时间","singer":"周杰伦"}\r\n{"song":"忘情水","singer":"刘德华"}\r\n{"song":"暗香","singer":"刘德华"}\r\n{"song":"逆光","singer":"梁静茹"}`

// 获取当前时间
func getCurTime()string{
	t := time.Now().Unix()
	s := strconv.FormatInt(t, 10)
	return s
}

// 计算checksum
func calcCheckSum(accountKey, nonce, curTime string)string{
	key := accountKey + nonce + curTime
	m := md5.Sum(([]byte)(key))
	mStr := hex.EncodeToString(m[:])

	return mStr
}

// 动态实体上传
func EntityUpload(resName string, persParam string, data string){
	uv := url.Values{}
	uv.Set("appid", APPID)
	uv.Set("res_name", resName)
	uv.Set("pers_param", persParam)
	uv.Set("data", data)

	s := uv.Encode()

	buf := strings.NewReader(s)

	r, err := http.NewRequest("POST", AIUIURL, buf)
	if err != nil{
		log.Println(err)
	}

	ct := getCurTime()

	r.Header.Add("X-NameSpace", RESNameSpace)
	r.Header.Add("X-Nonce", X_Nonce)
	r.Header.Add("X-CurTime", ct)
	r.Header.Add("X-CheckSum", calcCheckSum(AC_KEY, X_Nonce, ct))
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")

	c := http.Client{
		Timeout:5 * time.Second,
	}

	//dump请求信息
	dump, err := httputil.DumpRequestOut(r, true)
	if err != nil{
		log.Println(err)
	}

	log.Println(string(dump))

	resp, err := c.Do(r)

	//dump响应消息
	dumpResp, err := httputil.DumpResponse(resp, true)
	if err != nil{
		log.Println(err)
	}

	log.Println(string(dumpResp))

	/*
	if err != nil{
		log.Println(err)
	}else{
		d, err := ioutil.ReadAll(resp.Body)
		if err != nil{
			log.Println(err)
		}else {
			log.Println(string(d))
		}
	}
	*/
}
